<template>
  <div class="learning-path">
    <div class="path-header">
      <h1>学习路径</h1>
      <div class="path-actions">
        <el-radio-group v-model="currentCourse" @change="switchCourse">
          <el-radio-button v-for="course in courses" 
                          :key="course.id" 
                          :label="course.id">
            {{ course.name }}
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <!-- 学习者画像 -->
    <el-card class="learner-profile">
      <template #header>
        <div class="profile-header">
          <h3>学习者画像</h3>
          <el-button type="primary" text @click="updateProfile">更新画像</el-button>
        </div>
      </template>
      <el-row :gutter="20">
        <!-- 学习风格分析 -->
        <el-col :span="8">
          <div class="profile-section">
            <h4>学习风格分析</h4>
            <div class="style-analysis">
              <div class="style-item">
                <span class="style-label">认知方式</span>
                <el-tag>{{ learnerProfile.cognitiveStyle }}</el-tag>
              </div>
              <div class="style-progress">
                <div class="progress-item">
                  <span>视觉学习</span>
                  <el-progress :percentage="learnerProfile.visualLearning" />
                </div>
                <div class="progress-item">
                  <span>听觉学习</span>
                  <el-progress :percentage="learnerProfile.auditoryLearning" />
                </div>
                <div class="progress-item">
                  <span>实践学习</span>
                  <el-progress :percentage="learnerProfile.kineticLearning" />
                </div>
              </div>
            </div>
          </div>
        </el-col>
        
        <!-- 知识掌握分布 -->
        <el-col :span="8">
          <div class="profile-section">
            <h4>知识掌握分布</h4>
            <div class="knowledge-radar">
              <v-chart :option="radarOption" autoresize style="height: 200px;" />
            </div>
          </div>
        </el-col>
        
        <!-- 学习行为特征 -->
        <el-col :span="8">
          <div class="profile-section">
            <h4>学习行为特征</h4>
            <ul class="behavior-list">
              <li class="behavior-item">
                <span class="behavior-label">最佳学习时段</span>
                <span class="behavior-value">{{ learnerProfile.bestTimeSlot }}</span>
              </li>
              <li class="behavior-item">
                <span class="behavior-label">平均专注时长</span>
                <span class="behavior-value">{{ learnerProfile.avgFocusTime }}分钟</span>
              </li>
              <li class="behavior-item">
                <span class="behavior-label">学习规律性</span>
                <el-rate
                  v-model="learnerProfile.regularity"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </li>
              <li class="behavior-item">
                <span class="behavior-label">知识点关联度</span>
                <el-progress
                  :percentage="learnerProfile.knowledgeConnection"
                  :format="val => val + '%'"
                />
              </li>
            </ul>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 知识图谱展示区域 -->
    <div class="knowledge-map">
      <el-card class="map-container">
        <template #header>
          <div class="map-header">
            <h3>知识点关系图</h3>
            <div class="map-controls">
              <el-input
                v-model="searchQuery"
                placeholder="搜索知识点..."
                prefix-icon="Search"
                clearable
                @input="filterKnowledgePoints"
                class="search-input"
              />
              <el-select 
                v-model="difficultyFilter" 
                placeholder="难度筛选"
                clearable
                @change="filterKnowledgePoints"
              >
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </div>
            <div class="map-legend">
              <div class="legend-item">
                <span class="dot completed"></span>已掌握
              </div>
              <div class="legend-item">
                <span class="dot current"></span>正在学习
              </div>
              <div class="legend-item">
                <span class="dot locked"></span>待解锁
              </div>
            </div>
          </div>
        </template>
        <v-chart 
          class="chart" 
          :option="chartOption" 
          autoresize 
          @click="handleChartClick"
        />
        <div class="map-tips">
          <el-alert
            title="提示：点击知识点可查看详情，可以使用鼠标滚轮缩放图表，按住鼠标左键拖动图表"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </div>

    <!-- 学习建议区域 -->
    <el-row :gutter="20" class="suggestion-section">
      <el-col :span="16">
        <!-- 推荐学习路径 -->
        <el-card class="path-suggestion">
          <template #header>
            <h3>推荐学习路径</h3>
          </template>
          <el-steps direction="vertical" :active="currentStepIndex">
            <el-step 
              v-for="(step, index) in recommendedPath" 
              :key="index"
              :title="step.title"
              :description="step.description"
              :status="step.status"
            >
              <template #icon>
                <el-icon v-if="step.status === 'success'"><Check /></el-icon>
                <el-icon v-else-if="step.status === 'process'"><Loading /></el-icon>
                <el-icon v-else><Lock /></el-icon>
              </template>
            </el-step>
          </el-steps>
        </el-card>
      </el-col>

      <el-col :span="8">
        <!-- 学习进度概览 -->
        <el-card class="progress-overview">
          <template #header>
            <h3>学习进度概览</h3>
          </template>
          <div class="progress-stats">
            <div class="stat-item">
              <div class="stat-value">{{ stats.completedPoints }}</div>
              <div class="stat-label">已掌握知识点</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.totalPoints }}</div>
              <div class="stat-label">总知识点</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.estimatedDays }}天</div>
              <div class="stat-label">预计完成时间</div>
            </div>
          </div>
          <el-progress 
            :percentage="stats.totalProgress" 
            :format="format"
            class="total-progress"
          />
        </el-card>

        <!-- 学习建议卡片 -->
        <el-card class="learning-tips">
          <template #header>
            <h3>学习建议</h3>
          </template>
          <ul class="tips-list">
            <li v-for="(tip, index) in learningTips" 
                :key="index"
                class="tip-item">
              <el-icon><InfoFilled /></el-icon>
              <span>{{ tip }}</span>
            </li>
          </ul>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学习效果评估 -->
    <el-card class="learning-assessment">
      <template #header>
        <div class="assessment-header">
          <h3>学习效果评估</h3>
          <el-select v-model="assessmentPeriod" size="small">
            <el-option label="最近一周" value="week" />
            <el-option label="最近一月" value="month" />
            <el-option label="最近三月" value="quarter" />
          </el-select>
        </div>
      </template>
      
      <el-row :gutter="20">
        <!-- 学习效果趋势图 -->
        <el-col :span="16">
          <div class="trend-chart-container">
            <h4>学习效果趋势</h4>
            <v-chart :option="learningTrendOption" autoresize style="height: 300px;" />
          </div>
        </el-col>
        
        <!-- 学习效果指标 -->
        <el-col :span="8">
          <div class="metrics-container">
            <div v-for="metric in learningMetrics" :key="metric.name" class="metric-item">
              <div class="metric-header">
                <span>{{ metric.name }}</span>
                <el-tooltip :content="metric.description" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
              <div class="metric-value" :style="{ color: metric.color }">
                {{ metric.value }}{{ metric.unit }}
              </div>
              <div class="metric-trend">
                <el-tag :type="metric.trend > 0 ? 'success' : 'danger'" size="small">
                  {{ metric.trend > 0 ? '↑' : '↓' }} {{ Math.abs(metric.trend) }}%
                </el-tag>
                <span class="trend-period">较上期</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 学习效果详细分析 -->
      <div class="assessment-details">
        <el-divider>详细分析</el-divider>
        <el-collapse v-model="activeAnalysis">
          <el-collapse-item 
            v-for="analysis in assessmentAnalysis" 
            :key="analysis.id" 
            :title="analysis.title"
            :name="analysis.id"
          >
            <div class="analysis-content">
              <p class="analysis-description">{{ analysis.description }}</p>
              <div class="analysis-data">
                <el-progress
                  v-if="analysis.type === 'progress'"
                  :percentage="analysis.value"
                  :status="analysis.status"
                />
                <div v-else-if="analysis.type === 'comparison'" class="comparison-data">
                  <div class="comparison-item">
                    <div class="comparison-label">你的表现</div>
                    <div class="comparison-value">{{ analysis.yourValue }}</div>
                  </div>
                  <div class="comparison-item">
                    <div class="comparison-label">平均水平</div>
                    <div class="comparison-value">{{ analysis.avgValue }}</div>
                  </div>
                </div>
              </div>
              <ul class="improvement-suggestions">
                <li v-for="(suggestion, index) in analysis.suggestions" 
                    :key="index"
                    class="suggestion-item">
                  <el-icon><ArrowRight /></el-icon>
                  {{ suggestion }}
                </li>
              </ul>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { GraphChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'

// 注册 ECharts 必要组件
use([
  CanvasRenderer,
  GraphChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
])

const router = useRouter()
const currentCourse = ref(1)
const currentStepIndex = ref(2)
const searchQuery = ref('')
const difficultyFilter = ref('')

// 课程列表
const courses = ref([
  { id: 1, name: '数据结构与算法' },
  { id: 2, name: '计算机网络' },
  { id: 3, name: '计算机组成原理' },
  { id: 4, name: '操作系统' }
])

// 推荐学习路径
const recommendedPath = ref([
  {
    title: '基础数据结构',
    description: '已完成 数组、链表、栈、队列等基础数据结构的学习',
    status: 'success'
  },
  {
    title: '树结构',
    description: '正在学习 二叉树、平衡树等树形结构',
    status: 'process'
  },
  {
    title: '图论基础',
    description: '待学习 图的表示、遍历、最短路径等内容',
    status: 'wait'
  },
  {
    title: '高级数据结构',
    description: '待学习 红黑树、B树、跳表等高级数据结构',
    status: 'wait'
  }
])

// 学习统计
const stats = ref({
  completedPoints: 28,
  totalPoints: 56,
  estimatedDays: 45,
  totalProgress: 50
})

// 学习建议
const learningTips = ref([
  '建议先完成树结构的学习再进入图论章节',
  '可以通过每日练习来巩固已学知识点',
  '遇到困难可以查看相关视频讲解',
  '建议按照推荐路径循序渐进学习'
])

// 知识点数据
const knowledgePoints = ref([
  {
    id: '1',
    name: '数组',
    symbolSize: 50,
    category: 0,
    difficulty: 'easy',
    itemStyle: { color: '#67C23A' },
    value: {
      difficulty: 'easy',
      estimatedTime: '2小时',
      description: '数组是最基础的数据结构之一'
    }
  },
  {
    id: '2',
    name: '链表',
    symbolSize: 50,
    category: 0,
    difficulty: 'medium',
    itemStyle: { color: '#67C23A' },
    value: {
      difficulty: 'medium',
      estimatedTime: '3小时',
      description: '链表是一种线性数据结构'
    }
  },
  // ... 其他知识点
])

// 图表配置
const chartOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: (params) => {
      const { name, value } = params.data
      return `
        <div>
          <h4>${name}</h4>
          <p>难度：${value.difficulty}</p>
          <p>预计用时：${value.estimatedTime}</p>
          <p>${value.description}</p>
        </div>
      `
    }
  },
  series: [{
    type: 'graph',
    layout: 'force',
    animation: false,
    label: {
      show: true,
      position: 'right',
      formatter: '{b}'
    },
    draggable: true,
    roam: true,
    data: knowledgePoints.value,
    links: [
      { source: '1', target: '3' },
      { source: '2', target: '3' },
      { source: '3', target: '4' }
    ],
    categories: [
      { name: '已掌握' },
      { name: '正在学习' },
      { name: '待解锁' }
    ],
    force: {
      repulsion: 1000,
      edgeLength: 120
    }
  }]
})

// 处理知识点点击
const handleChartClick = (params) => {
  if (params.dataType === 'node') {
    const pointId = params.data.id
    router.push(`/point/${pointId}`)
  }
}

// 筛选知识点
const filterKnowledgePoints = () => {
  const filteredPoints = knowledgePoints.value.filter(point => {
    const matchesSearch = !searchQuery.value || 
      point.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesDifficulty = !difficultyFilter.value || 
      point.difficulty === difficultyFilter.value
    return matchesSearch && matchesDifficulty
  })
  
  chartOption.value.series[0].data = filteredPoints
}

// 监听筛选条件变化
watch([searchQuery, difficultyFilter], () => {
  filterKnowledgePoints()
})

const format = (percentage) => {
  return `${percentage}%`
}

const switchCourse = async (courseId) => {
  try {
    // 这里应该调用API获取新的知识图谱数据
    console.log('切换到课程:', courseId)
    // const response = await fetchKnowledgeGraph(courseId)
    // knowledgePoints.value = response.data
    // filterKnowledgePoints()
  } catch (error) {
    console.error('获取知识图谱失败:', error)
  }
}

// 学习效果评估相关数据
const assessmentPeriod = ref('week')
const activeAnalysis = ref(['1'])

// 学习效果趋势图配置
const learningTrendOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '知识掌握度',
      type: 'line',
      smooth: true,
      data: [70, 72, 75, 73, 78, 80, 82]
    },
    {
      name: '学习效率',
      type: 'line',
      smooth: true,
      data: [65, 68, 70, 72, 75, 74, 77]
    }
  ]
})

// 学习效果指标
const learningMetrics = ref([
  {
    name: '知识掌握度',
    value: 82,
    unit: '%',
    trend: 5,
    color: '#67C23A',
    description: '对所学知识点的整体理解和应用能力'
  },
  {
    name: '学习效率',
    value: 77,
    unit: '%',
    trend: -2,
    color: '#E6A23C',
    description: '单位时间内的知识点掌握数量'
  },
  {
    name: '知识连接度',
    value: 85,
    unit: '%',
    trend: 8,
    color: '#409EFF',
    description: '知识点之间的关联理解程度'
  }
])

// 详细分析数据
const assessmentAnalysis = ref([
  {
    id: '1',
    title: '知识掌握情况分析',
    type: 'progress',
    description: '本阶段的知识掌握情况良好，特别是在算法设计方面有显著提升。',
    value: 82,
    status: 'success',
    suggestions: [
      '建议多做一些综合性练习，加强知识点之间的联系',
      '可以尝试更难的算法题目来提升能力'
    ]
  },
  {
    id: '2',
    title: '学习效率对比',
    type: 'comparison',
    description: '与同水平学习者相比，你的学习效率略高于平均水平。',
    yourValue: '77%',
    avgValue: '72%',
    suggestions: [
      '建议合理安排学习时间，避免疲劳学习',
      '可以尝试番茄工作法来提高学习专注度'
    ]
  }
])

// 学习者画像数据
const learnerProfile = ref({
  cognitiveStyle: '视觉型学习者',
  visualLearning: 75,
  auditoryLearning: 45,
  kineticLearning: 60,
  bestTimeSlot: '09:00-11:00',
  avgFocusTime: 45,
  regularity: 4,
  knowledgeConnection: 78
})

// 雷达图配置
const radarOption = ref({
  radar: {
    indicator: [
      { name: '数据结构', max: 100 },
      { name: '算法设计', max: 100 },
      { name: '编程能力', max: 100 },
      { name: '问题分析', max: 100 },
      { name: '知识应用', max: 100 }
    ]
  },
  series: [{
    type: 'radar',
    data: [{
      value: [80, 65, 70, 85, 75],
      name: '知识掌握度',
      areaStyle: {
        color: 'rgba(64,158,255,0.2)'
      },
      lineStyle: {
        color: '#409EFF'
      }
    }]
  }]
})

// 更新学习者画像
const updateProfile = async () => {
  try {
    // 这里应该调用API更新学习者画像
    console.log('更新学习者画像')
  } catch (error) {
    console.error('更新失败:', error)
  }
}
</script>

<style scoped>
.learning-path {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.path-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.knowledge-map {
  margin-bottom: 20px;
}

.map-container {
  margin-bottom: 20px;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.map-legend {
  display: flex;
  gap: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  display: inline-block;
}

.dot.completed {
  background-color: #67C23A;
}

.dot.current {
  background-color: #409EFF;
}

.dot.locked {
  background-color: #909399;
}

.chart {
  height: 600px;
  cursor: pointer;
}

.suggestion-section {
  margin-top: 20px;
}

.progress-overview {
  margin-bottom: 20px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--primary-color);
}

.stat-label {
  color: var(--text-secondary);
  font-size: 14px;
  margin-top: 4px;
}

.total-progress {
  margin-top: 20px;
}

.tips-list {
  list-style: none;
  padding: 0;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 12px;
  color: var(--text-regular);
}

.tip-item .el-icon {
  color: var(--primary-color);
  margin-top: 3px;
}

.map-controls {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.search-input {
  width: 240px;
}

.map-tips {
  margin-top: 16px;
  text-align: center;
}

.learning-assessment {
  margin-top: 20px;
}
 
.assessment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
 
.metrics-container {
  padding: 16px;
}
 
.metric-item {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}
 
.metric-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
 
.metric-value {
  font-size: 24px;
  font-weight: bold;
  margin: 8px 0;
}
 
.metric-trend {
  display: flex;
  align-items: center;
  gap: 8px;
}
 
.trend-period {
  color: var(--text-secondary);
  font-size: 12px;
}
 
.assessment-details {
  margin-top: 20px;
}
 
.analysis-content {
  padding: 16px;
}
 
.analysis-description {
  color: var(--text-regular);
  margin-bottom: 16px;
}
 
.comparison-data {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
}
 
.comparison-item {
  text-align: center;
}
 
.comparison-label {
  color: var(--text-secondary);
  margin-bottom: 8px;
}
 
.comparison-value {
  font-size: 20px;
  font-weight: bold;
  color: var(--primary-color);
}
 
.improvement-suggestions {
  list-style: none;
  padding: 0;
  margin-top: 16px;
}
 
.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
  color: var(--text-regular);
}

.learner-profile {
  margin-bottom: 20px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-section {
  padding: 16px;
}

.profile-section h4 {
  margin-bottom: 16px;
  color: var(--text-primary);
}

.style-analysis {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.style-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.style-progress {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.progress-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.behavior-list {
  list-style: none;
  padding: 0;
}

.behavior-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.behavior-label {
  color: var(--text-regular);
}

.behavior-value {
  font-weight: bold;
  color: var(--text-primary);
}
</style>